package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.service.PayService;
import com.itheima.reggie.utils.PayUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired(required = false)
    private PayService payService;

    @GetMapping("/wxpay")
    public R<String> wxpay(HttpSession session, HttpServletRequest servletRequest, HttpServletResponse response) throws ServletException, IOException {
        String id = (String) session.getAttribute("id");
        BigDecimal amount = (BigDecimal) session.getAttribute("amount");
        String url = PayUtils.createOrder(id, 1);

        servletRequest.setAttribute("url",url);
        servletRequest.setAttribute("oid",id);
        servletRequest.setAttribute("amount",amount);

       // servletRequest.getRequestDispatcher("/wxpay.html").forward(servletRequest,response);

        return R.success(url);

    }

    @GetMapping("/findStatus")
    public R<String> findStatus(HttpSession session) {
        String id = (String) session.getAttribute("id");
        log.info(id);
        Boolean result = payService.findStatus(Long.parseLong(id));
        if (result){
            return R.success("支付成功");
        }else {
            return R.error("支付失败");
        }
    }
}
